'use client';

import { useState, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { DashboardLayout } from '@/components/layout/dashboard-layout';
import { AdminGuard } from '@/components/auth/PermissionGuard';
import { multiChainApi } from '@/lib/multi-chain-api';
import { useChain } from '@/context/ChainContext';
import { 
  Settings, Save, RefreshCw, Shield, Database, 
  Coins, Users, Bell, Globe, Lock, AlertCircle 
} from 'lucide-react';

interface SystemSettings {
  general: {
    system_name: string;
    system_version: string;
    maintenance_mode: boolean;
    registration_enabled: boolean;
    trading_enabled: boolean;
  };
  security: {
    min_password_length: number;
    require_2fa: boolean;
    session_timeout: number;
    max_login_attempts: number;
    ip_whitelist_enabled: boolean;
    allowed_ips: string[];
  };
  blockchain: {
    network: string;
    rpc_url: string;
    dtv_contract_address: string;
    staking_contract_address?: string; // Built into DTV token contract
    confirmations_required: number;
    gas_price_multiplier: number;
  };
  mining: {
    daily_pos_rate: number;
    mining_release_rate: number;
    referral_rates: {
      level_1: number;
      level_2: number;
      level_3: number;
      level_4: number;
      level_5: number;
    };
    min_stake_amount: number;
    max_stake_amount: number;
    reward_distribution_time: string;
  };
  referral: {
    max_referral_levels: number;
    referral_code_length: number;
    pop_qualification_threshold: number;
    pool_qualification_rules: {
      pool_1: number;
      pool_2: number;
      pool_3: number;
    };
  };
  dtvc: {
    exchange_rate: number;
    min_exchange_amount: number;
    max_exchange_amount: number;
    exchange_fee_percentage: number;
    exchange_enabled: boolean;
  };
  notifications: {
    email_enabled: boolean;
    sms_enabled: boolean;
    push_enabled: boolean;
    email_provider: string;
    sms_provider: string;
  };
}

interface SettingSection {
  id: string;
  title: string;
  description: string;
  icon: React.ElementType;
  color: string;
}

const settingSections: SettingSection[] = [
  {
    id: 'general',
    title: 'General Settings',
    description: 'Basic system configuration',
    icon: Settings,
    color: 'text-blue-600'
  },
  {
    id: 'security',
    title: 'Security Settings',
    description: 'Authentication and access control',
    icon: Shield,
    color: 'text-red-600'
  },
  {
    id: 'blockchain',
    title: 'Blockchain Settings',
    description: 'Web3 and smart contract configuration',
    icon: Database,
    color: 'text-purple-600'
  },
  {
    id: 'mining',
    title: 'Mining Settings',
    description: 'Staking and reward parameters',
    icon: Coins,
    color: 'text-green-600'
  },
  {
    id: 'referral',
    title: 'Referral Settings',
    description: 'Referral system configuration',
    icon: Users,
    color: 'text-yellow-600'
  },
  {
    id: 'dtvc',
    title: 'DTVC Settings',
    description: 'DTV Credits exchange configuration',
    icon: Coins,
    color: 'text-indigo-600'
  },
  {
    id: 'notifications',
    title: 'Notification Settings',
    description: 'Communication channels configuration',
    icon: Bell,
    color: 'text-pink-600'
  }
];

export default function SettingsPage() {
  const { currentChain } = useChain();
  const [activeSection, setActiveSection] = useState('general');
  const [formData, setFormData] = useState<Partial<SystemSettings>>({});
  const [unsavedChanges, setUnsavedChanges] = useState(false);
  const queryClient = useQueryClient();

  // Fetch system settings
  const { data: settings, isLoading, refetch } = useQuery<SystemSettings>({
    queryKey: ['system-settings', currentChain],
    queryFn: async () => {
      const client = multiChainApi.getClient(currentChain);
      const response = await client.get('/api/v1/admin/settings');
      return response.data;
    },
  });

  // Update form data when settings change
  useEffect(() => {
    if (settings) {
      setFormData(settings);
    }
  }, [settings]);

  // Update settings mutation
  const updateMutation = useMutation({
    mutationFn: async (section: string) => {
      const sectionData = formData[section as keyof SystemSettings];
      const client = multiChainApi.getClient(currentChain);
      const response = await client.put(`/api/v1/admin/settings/${section}`, sectionData);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['system-settings'] });
      setUnsavedChanges(false);
      refetch();
    },
  });

  // Reset settings mutation
  const resetMutation = useMutation({
    mutationFn: async (section: string) => {
      const client = multiChainApi.getClient(currentChain);
      const response = await client.post(`/api/v1/admin/settings/${section}/reset`);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['system-settings'] });
      setUnsavedChanges(false);
      refetch();
    },
  });

  const handleInputChange = (section: string, field: string, value: any) => {
    setFormData(prev => ({
      ...prev,
      [section]: {
        ...prev[section as keyof SystemSettings],
        [field]: value
      }
    }));
    setUnsavedChanges(true);
  };

  const handleNestedInputChange = (section: string, parentField: string, field: string, value: any) => {
    setFormData(prev => ({
      ...prev,
      [section]: {
        ...prev[section as keyof SystemSettings],
        [parentField]: {
          ...(prev[section as keyof SystemSettings] as any)?.[parentField],
          [field]: value
        }
      }
    }));
    setUnsavedChanges(true);
  };

  const handleSave = () => {
    updateMutation.mutate(activeSection);
  };

  const handleReset = () => {
    if (confirm('Are you sure you want to reset these settings to default values?')) {
      resetMutation.mutate(activeSection);
    }
  };

  const renderGeneralSettings = () => (
    <div className="space-y-4">
      <div>
        <label className="block text-sm font-medium mb-1">System Name</label>
        <input
          type="text"
          className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          value={formData.general?.system_name || ''}
          onChange={(e) => handleInputChange('general', 'system_name', e.target.value)}
        />
      </div>
      <div>
        <label className="block text-sm font-medium mb-1">System Version</label>
        <input
          type="text"
          className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          value={formData.general?.system_version || ''}
          readOnly
        />
      </div>
      <div className="space-y-2">
        <label className="flex items-center gap-2">
          <input
            type="checkbox"
            className="rounded"
            checked={formData.general?.maintenance_mode || false}
            onChange={(e) => handleInputChange('general', 'maintenance_mode', e.target.checked)}
          />
          <span className="text-sm font-medium">Maintenance Mode</span>
        </label>
        <p className="text-xs text-muted-foreground ml-6">
          Enable maintenance mode to prevent user access
        </p>
      </div>
      <div className="space-y-2">
        <label className="flex items-center gap-2">
          <input
            type="checkbox"
            className="rounded"
            checked={formData.general?.registration_enabled || false}
            onChange={(e) => handleInputChange('general', 'registration_enabled', e.target.checked)}
          />
          <span className="text-sm font-medium">Registration Enabled</span>
        </label>
        <p className="text-xs text-muted-foreground ml-6">
          Allow new users to register
        </p>
      </div>
      <div className="space-y-2">
        <label className="flex items-center gap-2">
          <input
            type="checkbox"
            className="rounded"
            checked={formData.general?.trading_enabled || false}
            onChange={(e) => handleInputChange('general', 'trading_enabled', e.target.checked)}
          />
          <span className="text-sm font-medium">Trading Enabled</span>
        </label>
        <p className="text-xs text-muted-foreground ml-6">
          Enable DTVC to DTV exchange functionality
        </p>
      </div>
    </div>
  );

  const renderSecuritySettings = () => (
    <div className="space-y-4">
      <div>
        <label className="block text-sm font-medium mb-1">Minimum Password Length</label>
        <input
          type="number"
          className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          value={formData.security?.min_password_length || 8}
          onChange={(e) => handleInputChange('security', 'min_password_length', parseInt(e.target.value))}
          min={6}
          max={32}
        />
      </div>
      <div>
        <label className="block text-sm font-medium mb-1">Session Timeout (minutes)</label>
        <input
          type="number"
          className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          value={formData.security?.session_timeout || 60}
          onChange={(e) => handleInputChange('security', 'session_timeout', parseInt(e.target.value))}
          min={5}
          max={1440}
        />
      </div>
      <div>
        <label className="block text-sm font-medium mb-1">Max Login Attempts</label>
        <input
          type="number"
          className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          value={formData.security?.max_login_attempts || 5}
          onChange={(e) => handleInputChange('security', 'max_login_attempts', parseInt(e.target.value))}
          min={3}
          max={10}
        />
      </div>
      <div className="space-y-2">
        <label className="flex items-center gap-2">
          <input
            type="checkbox"
            className="rounded"
            checked={formData.security?.require_2fa || false}
            onChange={(e) => handleInputChange('security', 'require_2fa', e.target.checked)}
          />
          <span className="text-sm font-medium">Require 2FA</span>
        </label>
        <p className="text-xs text-muted-foreground ml-6">
          Require two-factor authentication for all users
        </p>
      </div>
      <div className="space-y-2">
        <label className="flex items-center gap-2">
          <input
            type="checkbox"
            className="rounded"
            checked={formData.security?.ip_whitelist_enabled || false}
            onChange={(e) => handleInputChange('security', 'ip_whitelist_enabled', e.target.checked)}
          />
          <span className="text-sm font-medium">IP Whitelist Enabled</span>
        </label>
        <p className="text-xs text-muted-foreground ml-6">
          Only allow access from whitelisted IP addresses
        </p>
      </div>
    </div>
  );

  const renderBlockchainSettings = () => (
    <div className="space-y-4">
      <div>
        <label className="block text-sm font-medium mb-1">Network</label>
        <select
          className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          value={formData.blockchain?.network || 'ethereum'}
          onChange={(e) => handleInputChange('blockchain', 'network', e.target.value)}
        >
          <option value="ethereum">Ethereum Mainnet</option>
          <option value="goerli">Goerli Testnet</option>
          <option value="sepolia">Sepolia Testnet</option>
          <option value="polygon">Polygon</option>
          <option value="bsc">BSC</option>
        </select>
      </div>
      <div>
        <label className="block text-sm font-medium mb-1">RPC URL</label>
        <input
          type="text"
          className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          value={formData.blockchain?.rpc_url || ''}
          onChange={(e) => handleInputChange('blockchain', 'rpc_url', e.target.value)}
          placeholder="https://..."
        />
      </div>
      <div>
        <label className="block text-sm font-medium mb-1">DTV Contract Address</label>
        <input
          type="text"
          className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 font-mono text-sm"
          value={formData.blockchain?.dtv_contract_address || ''}
          onChange={(e) => handleInputChange('blockchain', 'dtv_contract_address', e.target.value)}
          placeholder="0x..."
        />
      </div>
      <div>
        <label className="block text-sm font-medium mb-1">Staking Contract Address</label>
        <div className="w-full px-3 py-2 border rounded-md bg-muted text-muted-foreground font-mono text-sm">
          Built into DTV Token Contract
        </div>
        <p className="text-xs text-muted-foreground mt-1">
          Mining/staking functionality is built directly into the DTV token contract. No separate staking contract is needed.
        </p>
      </div>
      <div>
        <label className="block text-sm font-medium mb-1">Confirmations Required</label>
        <input
          type="number"
          className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          value={formData.blockchain?.confirmations_required || 12}
          onChange={(e) => handleInputChange('blockchain', 'confirmations_required', parseInt(e.target.value))}
          min={1}
          max={100}
        />
      </div>
      <div>
        <label className="block text-sm font-medium mb-1">Gas Price Multiplier</label>
        <input
          type="number"
          className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          value={formData.blockchain?.gas_price_multiplier || 1.2}
          onChange={(e) => handleInputChange('blockchain', 'gas_price_multiplier', parseFloat(e.target.value))}
          min={1}
          max={5}
          step={0.1}
        />
      </div>
    </div>
  );

  const renderMiningSettings = () => (
    <div className="space-y-4">
      <div>
        <label className="block text-sm font-medium mb-1">Daily POS Rate (%)</label>
        <input
          type="number"
          className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          value={(formData.mining?.daily_pos_rate || 0.005) * 100}
          onChange={(e) => handleInputChange('mining', 'daily_pos_rate', parseFloat(e.target.value) / 100)}
          min={0}
          max={10}
          step={0.01}
        />
      </div>
      <div>
        <label className="block text-sm font-medium mb-1">Mining Release Rate (%) - Yesterday Mining Output</label>
        <input
          type="number"
          className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          value={(formData.mining?.mining_release_rate || 0.011) * 100}
          onChange={(e) => handleInputChange('mining', 'mining_release_rate', parseFloat(e.target.value) / 100)}
          min={0}
          max={10}
          step={0.01}
        />
        <p className="text-xs text-muted-foreground mt-1">
          This rate determines the "Yesterday Mining Output" calculation: Total Staked × Mining Release Rate
        </p>
      </div>
      <div>
        <label className="block text-sm font-medium mb-1">Reward Distribution Time</label>
        <input
          type="time"
          className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          value={formData.mining?.reward_distribution_time || '08:00'}
          onChange={(e) => handleInputChange('mining', 'reward_distribution_time', e.target.value)}
        />
      </div>
      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-medium mb-1">Min Stake Amount</label>
          <input
            type="number"
            className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            value={formData.mining?.min_stake_amount || 100}
            onChange={(e) => handleInputChange('mining', 'min_stake_amount', parseFloat(e.target.value))}
            min={0}
          />
        </div>
        <div>
          <label className="block text-sm font-medium mb-1">Max Stake Amount</label>
          <input
            type="number"
            className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            value={formData.mining?.max_stake_amount || 1000000}
            onChange={(e) => handleInputChange('mining', 'max_stake_amount', parseFloat(e.target.value))}
            min={0}
          />
        </div>
      </div>
      <div>
        <h4 className="font-medium mb-2">Referral Rates by Level</h4>
        <div className="space-y-2">
          {[1, 2, 3, 4, 5].map((level) => (
            <div key={level} className="flex items-center gap-4">
              <label className="text-sm w-20">Level {level}:</label>
              <input
                type="number"
                className="flex-1 px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                value={(formData.mining?.referral_rates?.[`level_${level}` as keyof typeof formData.mining.referral_rates] || 0) * 100}
                onChange={(e) => handleNestedInputChange('mining', 'referral_rates', `level_${level}`, parseFloat(e.target.value) / 100)}
                min={0}
                max={100}
                step={0.1}
              />
              <span className="text-sm text-muted-foreground">%</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );

  const renderReferralSettings = () => (
    <div className="space-y-4">
      <div>
        <label className="block text-sm font-medium mb-1">Max Referral Levels</label>
        <input
          type="number"
          className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          value={formData.referral?.max_referral_levels || 5}
          onChange={(e) => handleInputChange('referral', 'max_referral_levels', parseInt(e.target.value))}
          min={1}
          max={10}
        />
      </div>
      <div>
        <label className="block text-sm font-medium mb-1">Referral Code Length</label>
        <input
          type="number"
          className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          value={formData.referral?.referral_code_length || 8}
          onChange={(e) => handleInputChange('referral', 'referral_code_length', parseInt(e.target.value))}
          min={6}
          max={16}
        />
      </div>
      <div>
        <label className="block text-sm font-medium mb-1">POP Qualification Threshold</label>
        <input
          type="number"
          className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          value={formData.referral?.pop_qualification_threshold || 1000}
          onChange={(e) => handleInputChange('referral', 'pop_qualification_threshold', parseFloat(e.target.value))}
          min={0}
        />
      </div>
      <div>
        <h4 className="font-medium mb-2">Pool Qualification Rules</h4>
        <div className="space-y-2">
          {[1, 2, 3].map((pool) => (
            <div key={pool} className="flex items-center gap-4">
              <label className="text-sm w-20">Pool {pool}:</label>
              <input
                type="number"
                className="flex-1 px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                value={formData.referral?.pool_qualification_rules?.[`pool_${pool}` as keyof typeof formData.referral.pool_qualification_rules] || 0}
                onChange={(e) => handleNestedInputChange('referral', 'pool_qualification_rules', `pool_${pool}`, parseInt(e.target.value))}
                min={0}
              />
              <span className="text-sm text-muted-foreground">referrals</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );

  const renderDTVCSettings = () => (
    <div className="space-y-4">
      <div>
        <label className="block text-sm font-medium mb-1">Exchange Rate (DTVC to DTV)</label>
        <input
          type="number"
          className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          value={formData.dtvc?.exchange_rate || 1000}
          onChange={(e) => handleInputChange('dtvc', 'exchange_rate', parseFloat(e.target.value))}
          min={1}
        />
      </div>
      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-medium mb-1">Min Exchange Amount</label>
          <input
            type="number"
            className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            value={formData.dtvc?.min_exchange_amount || 1000}
            onChange={(e) => handleInputChange('dtvc', 'min_exchange_amount', parseFloat(e.target.value))}
            min={0}
          />
        </div>
        <div>
          <label className="block text-sm font-medium mb-1">Max Exchange Amount</label>
          <input
            type="number"
            className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            value={formData.dtvc?.max_exchange_amount || 100000}
            onChange={(e) => handleInputChange('dtvc', 'max_exchange_amount', parseFloat(e.target.value))}
            min={0}
          />
        </div>
      </div>
      <div>
        <label className="block text-sm font-medium mb-1">Exchange Fee (%)</label>
        <input
          type="number"
          className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          value={formData.dtvc?.exchange_fee_percentage || 5}
          onChange={(e) => handleInputChange('dtvc', 'exchange_fee_percentage', parseFloat(e.target.value))}
          min={0}
          max={100}
          step={0.1}
        />
      </div>
      <div className="space-y-2">
        <label className="flex items-center gap-2">
          <input
            type="checkbox"
            className="rounded"
            checked={formData.dtvc?.exchange_enabled || false}
            onChange={(e) => handleInputChange('dtvc', 'exchange_enabled', e.target.checked)}
          />
          <span className="text-sm font-medium">Exchange Enabled</span>
        </label>
        <p className="text-xs text-muted-foreground ml-6">
          Enable DTVC to DTV exchange functionality
        </p>
      </div>
    </div>
  );

  const renderNotificationSettings = () => (
    <div className="space-y-4">
      <div className="space-y-2">
        <label className="flex items-center gap-2">
          <input
            type="checkbox"
            className="rounded"
            checked={formData.notifications?.email_enabled || false}
            onChange={(e) => handleInputChange('notifications', 'email_enabled', e.target.checked)}
          />
          <span className="text-sm font-medium">Email Notifications</span>
        </label>
      </div>
      <div className="space-y-2">
        <label className="flex items-center gap-2">
          <input
            type="checkbox"
            className="rounded"
            checked={formData.notifications?.sms_enabled || false}
            onChange={(e) => handleInputChange('notifications', 'sms_enabled', e.target.checked)}
          />
          <span className="text-sm font-medium">SMS Notifications</span>
        </label>
      </div>
      <div className="space-y-2">
        <label className="flex items-center gap-2">
          <input
            type="checkbox"
            className="rounded"
            checked={formData.notifications?.push_enabled || false}
            onChange={(e) => handleInputChange('notifications', 'push_enabled', e.target.checked)}
          />
          <span className="text-sm font-medium">Push Notifications</span>
        </label>
      </div>
      <div>
        <label className="block text-sm font-medium mb-1">Email Provider</label>
        <select
          className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          value={formData.notifications?.email_provider || 'sendgrid'}
          onChange={(e) => handleInputChange('notifications', 'email_provider', e.target.value)}
        >
          <option value="sendgrid">SendGrid</option>
          <option value="mailgun">Mailgun</option>
          <option value="ses">Amazon SES</option>
          <option value="smtp">SMTP</option>
        </select>
      </div>
      <div>
        <label className="block text-sm font-medium mb-1">SMS Provider</label>
        <select
          className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          value={formData.notifications?.sms_provider || 'twilio'}
          onChange={(e) => handleInputChange('notifications', 'sms_provider', e.target.value)}
        >
          <option value="twilio">Twilio</option>
          <option value="nexmo">Nexmo</option>
          <option value="sns">Amazon SNS</option>
        </select>
      </div>
    </div>
  );

  const renderSettingsContent = () => {
    switch (activeSection) {
      case 'general':
        return renderGeneralSettings();
      case 'security':
        return renderSecuritySettings();
      case 'blockchain':
        return renderBlockchainSettings();
      case 'mining':
        return renderMiningSettings();
      case 'referral':
        return renderReferralSettings();
      case 'dtvc':
        return renderDTVCSettings();
      case 'notifications':
        return renderNotificationSettings();
      default:
        return null;
    }
  };

  return (
    <DashboardLayout>
      <AdminGuard>
        <div className="space-y-6">
        {/* Header */}
        <div className="flex justify-between items-center">
          <div>
            <h1 className="text-3xl font-bold tracking-tight">System Settings</h1>
            <p className="text-muted-foreground">
              Configure system parameters and preferences
            </p>
          </div>
          {unsavedChanges && (
            <div className="flex items-center gap-2 text-yellow-600">
              <AlertCircle className="h-4 w-4" />
              <span className="text-sm">You have unsaved changes</span>
            </div>
          )}
        </div>

        <div className="grid gap-6 lg:grid-cols-4">
          {/* Settings Navigation */}
          <Card className="lg:col-span-1">
            <CardHeader>
              <CardTitle>Settings Sections</CardTitle>
            </CardHeader>
            <CardContent className="p-2">
              <nav className="space-y-1">
                {settingSections.map((section) => {
                  const Icon = section.icon;
                  return (
                    <button
                      key={section.id}
                      onClick={() => setActiveSection(section.id)}
                      className={`w-full flex items-center gap-3 px-3 py-2 text-sm font-medium rounded-md transition-colors ${
                        activeSection === section.id
                          ? 'bg-primary text-primary-foreground'
                          : 'hover:bg-muted'
                      }`}
                    >
                      <Icon className={`h-4 w-4 ${activeSection === section.id ? '' : section.color}`} />
                      <span>{section.title}</span>
                    </button>
                  );
                })}
              </nav>
            </CardContent>
          </Card>

          {/* Settings Content */}
          <Card className="lg:col-span-3">
            <CardHeader>
              <div className="flex justify-between items-center">
                <div>
                  <CardTitle>
                    {settingSections.find(s => s.id === activeSection)?.title}
                  </CardTitle>
                  <CardDescription>
                    {settingSections.find(s => s.id === activeSection)?.description}
                  </CardDescription>
                </div>
                <div className="flex gap-2">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={handleReset}
                    disabled={resetMutation.isPending}
                  >
                    <RefreshCw className="h-4 w-4 mr-2" />
                    Reset
                  </Button>
                  <Button
                    size="sm"
                    onClick={handleSave}
                    disabled={!unsavedChanges || updateMutation.isPending}
                  >
                    <Save className="h-4 w-4 mr-2" />
                    Save Changes
                  </Button>
                </div>
              </div>
            </CardHeader>
            <CardContent>
              {isLoading ? (
                <div className="text-center p-8">Loading settings...</div>
              ) : (
                renderSettingsContent()
              )}
            </CardContent>
          </Card>
        </div>
        </div>
      </AdminGuard>
    </DashboardLayout>
  );
}